<?php
require_once "../includes/config.php";
require_once "../includes/functions.php";
require_once('AmazonAPI/.config.inc.php');
ob_start();
session_start();
$sessid=session_id();
$msg = "";

$service = new AmazonAPI_FPS_Client(AWS_ACCESS_KEY_ID, 
                                       AWS_SECRET_ACCESS_KEY);
$request =  new AmazonAPI_FPS_Model_PayRequest();



/*function invokePay(AmazonAPI_FPS_Interface $service, $request) 
{
  try {
		  $response = $service->pay($request);
		  $payResult = $response->getPayResult();
		  $re_arr = array($payResult->getTransactionId(), $payResult->getTransactionStatus());
		  return $re_arr;		   

 } catch (AmazonAPI_FPS_Exception $ex) {
	 	  return "Failure";
 }
}*/

if(isset($_REQUEST['signature']) && !empty($_REQUEST['signature'])) {
	$tokenID = $_REQUEST['tokenID'];
	$callerReference = $_REQUEST['callerReference'];
	//print_r($_SESSION); exit;
									   
	$total_recipients = count($_SESSION['recipient_tokens']);
	$loop_limit = ($total_recipients - 1);
	for($i=0;$i<=$loop_limit;$i++){
		
		//echo $_SESSION['recipient_tokens'][$i]."<br />"; exit;
		$request->setCallerDescription('Swapen');
		$request->setCallerReference("swapen".rand());
		
		$request->setMarketplaceVariableFee('2.9');
		$request->setRecipientTokenId($_SESSION['recipient_tokens'][$i]);
		
		$request->setSenderTokenId($tokenID);//set the proper senderToken here.
		
		$amount = new AmazonAPI_FPS_Model_Amount();
		$amount->setCurrencyCode("USD");
		$amount->setValue($_SESSION['recipient_amounts'][$i]); //set the transaction amount here;
		
		$request->setTransactionAmount($amount);
	
	 // object or array of parameters
	  	$return = invokePay($service, $request);
		//$return=true;		
		
				
		if($return){
		
			//$sqlSelItem_comm="SELECT * FROM tbl_users where item_id=".$_SESSION['item_arr'][$i]." ";
//			$rstSelItem_comm=mysql_query($sqlSelItem_comm);
//			$rowSelItem_comm=mysql_fetch_array($rstSelItem_comm);
		
			echo $q = "Update tbl_refer_comm SET
					ref_transaction_id = '".$return[1]."',
					paid_date=Now(),isPaid='1'
					where refer_by_user_id='".$_SESSION['user_id_arr'][$i]."'
					and isPaid='2' ";
			mysql_query($q);			
						
			$_SESSION['order_msg'] = "Your transaction is successfull";
			header("location:index.php?refer_withdraw");
		}
	}
	//get users order status
	/*$oq = "SELECT * FROM tbl_orders WHERE ordered_by = '".$_SESSION['user_id']."' AND order_date = '".date('Y-m-d')."'";
	$or = mysql_query($oq) or die(mysql_error($oq));
	$oc = mysql_num_rows($or);
	if($oc == 0){
		$_SESSION['cart_msg'] = "Your transaction is not successfull";
		header("location:index.php?cart");
	}else{
		if(empty($msg)){
			$_SESSION['order_msg'] = "Your transaction is successfull";		
		}else{
			$_SESSION['order_msg'] = $msg;
		}
		header("location:index.php?order");
	}*/
	
	//use the above token ID to pay
}
function invokePay(AmazonAPI_FPS_Interface $service, $request) 
  {
      try {
              $response = $service->pay($request);
			  //$res_arr = array();
			  if($response){
			  	$payResult = $response->getPayResult();
				//$PayResult = $response->getPayResult();
				$TransactionId = $payResult->getTransactionId();
				$TransactionStatus = $payResult->getTransactionStatus();
				$responseMetadata = $response->getResponseMetadata();
				$RequestId = $responseMetadata->getRequestId();
			  	$res_arr = array($PayResult,
								 $TransactionId,
								 $TransactionStatus,
								 $RequestId
				);
			  }
			  return $res_arr;
              
                

     } catch (AmazonAPI_FPS_Exception $ex) {
         echo("Caught Exception: " . $ex->getMessage() . "\n");
         echo("Response Status Code: " . $ex->getStatusCode() . "\n");
         echo("Error Code: " . $ex->getErrorCode() . "\n");
         echo("Error Type: " . $ex->getErrorType() . "\n");
         echo("Request ID: " . $ex->getRequestId() . "\n");
         echo("XML: " . $ex->getXML() . "\n");
		 return false;
     }
 }
?>